package cn.wenhe9.novel.service.impl;

import cn.wenhe9.novel.constant.DatabaseConsts;
import cn.wenhe9.novel.domain.dto.NewsInfoDto;
import cn.wenhe9.novel.domain.entity.news.NewsContent;
import cn.wenhe9.novel.domain.entity.news.NewsInfo;
import cn.wenhe9.novel.manager.NewsCacheManager;
import cn.wenhe9.novel.mapper.NewsContentMapper;
import cn.wenhe9.novel.mapper.NewsInfoMapper;
import cn.wenhe9.novel.result.ResultResponse;
import cn.wenhe9.novel.service.NewsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 新闻模块 服务实现类
 *
 * @author DuJinliang
 * 2022/5/18
 */
@Service
public class NewsServiceImpl implements NewsService {

    @Resource
    private NewsCacheManager newsCacheManager;

    @Resource
    private NewsInfoMapper newsInfoMapper;

    @Resource
    private NewsContentMapper newsContentMapper;

    @Override
    public ResultResponse<List<NewsInfoDto>> listLatestNews() {
        return ResultResponse.ok(newsCacheManager.listLatestNews());
    }

    @Override
    public ResultResponse<NewsInfoDto> getNews(Long id) {
        NewsInfo newsInfo = newsInfoMapper.selectById(id);
        QueryWrapper<NewsContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(DatabaseConsts.NewsContentTable.COLUMN_NEWS_ID, id)
                .last(DatabaseConsts.SqlEnum.LIMIT_1.getSql());
        NewsContent newsContent = newsContentMapper.selectOne(queryWrapper);
        return ResultResponse.ok(NewsInfoDto.builder()
                .title(newsInfo.getTitle())
                .sourceName(newsInfo.getSourceName())
                .updateTime(newsInfo.getUpdateTime())
                .content(newsContent.getContent())
                .build());
    }
}
